package com.xunqi.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunqi.eduservice.entity.EduChapter;
import com.xunqi.eduservice.entity.EduVideo;
import com.xunqi.eduservice.entity.chapter.ChapterVo;
import com.xunqi.eduservice.entity.chapter.VideoVo;
import com.xunqi.eduservice.mapper.EduChapterMapper;
import com.xunqi.eduservice.mapper.EduVideoMapper;
import com.xunqi.eduservice.service.EduChapterService;
import com.xunqi.servicebase.exception.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author 夏沫止水
 * @since 2020-07-31
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoMapper eduVideoMapper;

    /**
     * 根据课程id，查询课程大纲列表
     * @param courseId
     * @return
     */
    @Override
    public List<ChapterVo> getChapterVideo(String courseId) {

        //根据课程id查询出对应的课程章节
        List<EduChapter> eduChapters = this.baseMapper.selectList(
                new QueryWrapper<EduChapter>().eq("course_id",courseId));

        List<ChapterVo> chapterVoList = eduChapters.stream().map(e -> {
            ChapterVo chapterVo = new ChapterVo();
            chapterVo.setId(e.getId());
            chapterVo.setTitle(e.getTitle());

            //根据章节id查询出对应的课程视频
            List<EduVideo> eduVideos = eduVideoMapper.selectList(new QueryWrapper<EduVideo>().eq("chapter_id", e.getId()));
            List<VideoVo> videoVoList = eduVideos.stream().filter(f -> f.getChapterId().equals(chapterVo.getId())).map(v -> {
                VideoVo videoVo = new VideoVo();
                videoVo.setId(v.getId());
                videoVo.setTitle(v.getTitle());
                videoVo.setVideoSourceId(v.getVideoSourceId());
                return videoVo;
            }).collect(Collectors.toList());

            chapterVo.setChildren(videoVoList);

            return chapterVo;
        }).collect(Collectors.toList());

        return chapterVoList;
    }

    @Override
    public boolean deleteChapter(String chapterId) {
        //先查询小节,如果有数据不进行删除
        Integer count = eduVideoMapper.selectCount(new QueryWrapper<EduVideo>().eq("chapter_id", chapterId));

        if (count > 0) {
            throw new GuliException(20001,"章节下有小节内容，不允许删除");
        }

        //删除章节内容
        return this.baseMapper.deleteById(chapterId) > 0;
    }
}
